#include <stdio.h>
#include <linux/ioctl.h>
#include <sys/soundcard.h>
#include <fcntl.h>

#define ENABLE_PLAY        0
#define ENABLE_RECORD      1
#define DEVICE_NAME        "/dev/dsp2"
#define PCM_READ         0
#define PCM_WRITE        1
#define SAMPLERATE     16000 //定义采样率
#define READMSFORONCE     10 //采样周期(ms)


int main(int argc, char **argv)
{
#if PCM_WRITE || PCM_READ
    FILE *fprecord = NULL;
#endif
    char buffer[SAMPLERATE/1000*READMSFORONCE*sizeof(short)];
    int fdsound = 0;
    int fdsoundplay = 0;
    int Frequency = SAMPLERATE;
    int format = AFMT_S16_LE;
    int channels = 1;
    int setting = 640;

#if ENABLE_RECORD
    fdsound = open(DEVICE_NAME, O_RDONLY);
    if(fdsound<0)
    {
       perror("以只写方式打开音频设备");
       return -1;
    }
#endif
    
#if ENABLE_PLAY
    fdsoundplay = open(DEVICE_NAME, O_WRONLY);/*只写方式打开设备*/
    if(fdsoundplay<0)
    {
       perror("以只写方式打开音频设备");
       return -1;
    }
#endif

#if PCM_WRITE
    fprecord = fopen("r.pcm", "wb");
#elif PCM_READ
    fprecord = fopen("r.pcm", "rb");    
#endif
    
#if ENABLE_RECORD
    printf("设置读音频设备参数\n");
    ioctl(fdsound, SNDCTL_DSP_SPEED, &Frequency);//采样频率
    ioctl(fdsound, SNDCTL_DSP_SETFMT, &format);//音频设备位宽
    ioctl(fdsound, SNDCTL_DSP_CHANNELS, &channels);//音频设备通道
    ioctl(fdsound, SNDCTL_DSP_SETFRAGMENT, &setting);//采样缓冲区
#endif
    
#if ENABLE_PLAY
    printf("设置写音频设备参数\n");
    ioctl(fdsoundplay, SNDCTL_DSP_SPEED, &Frequency);//采样频率
    ioctl(fdsoundplay, SNDCTL_DSP_SETFMT, &format);//音频设备位宽
    ioctl(fdsoundplay, SNDCTL_DSP_CHANNELS, &channels);//音频设备通道
    ioctl(fdsoundplay, SNDCTL_DSP_SETFRAGMENT, &setting);//采样缓冲区
#endif
    printf("sizeof(buffer)=%d, SAMPLERATE/1000*READMSFORONCE*sizeof(short)=%d\n", sizeof(buffer), SAMPLERATE/1000*READMSFORONCE*sizeof(short));
    while(1)
    {
#if ENABLE_RECORD
        if(read(fdsound, buffer, sizeof(buffer)) < 0)
        {
            perror("读声卡数据");
        }
#if PCM_WRITE            
        fwrite(buffer, sizeof(buffer), 1, fprecord);        
#endif        
#endif
        
#if ENABLE_PLAY
        printf("1111111\n");
#if PCM_READ
        printf("2222\n");            
        fread(buffer, sizeof(buffer), 1, fprecord);        
        printf("333\n");        
#endif        
        if(write(fdsoundplay, buffer, sizeof(buffer)) < 0)
        {    
            perror("音频设备写错误\n");
        }
#endif
    }
#if ENABLE_RECORD    
    close(fdsound);
#endif

#if ENABLE_PLAY    
    close(fdsoundplay);
#endif
    
#if PCM_WRITE || PCM_READ
    fclose(fprecord);
#endif    
}
